import { createStore } from 'vuex'
import { login, getManagerInfo } from '@/api/manager.js'
import { setToken,removeToken } from "@/composables/auth.js"
const store = createStore({
    state () {
      return {
        // user
        user:{},
        asideWidth:'250px',
        menus:[],
        ruleNames:[]
      }
    },
    mutations: {
        // 记录用户信息
        SetUserInfo(state,user){
            state.user=user
        },
        // 展开收起侧边栏
        ControlAside(state){
          state.asideWidth=state.asideWidth =='250px'?'64px':'250px'

        },
        // 设置菜单
        SetMenu(state,menus){
          state.menus=menus
        },
        // 设置权限
        SetRuleNames(state,ruleNames){
          state.ruleNames=ruleNames
        }

    },
    actions:{ 
      // login
      login({commit},{username,password}){
        return new Promise((resolve,reject)=>{
          login(username,password).then(res=>{
            setToken(res.token)
            resolve(res)
            

          }).catch(err=>reject(err))

        })

      },
      // 获取当前用户信息
      getInfo({commit}){
       return new Promise((resolve,reject)=>{
        getManagerInfo().then(res=>{
          commit("SetUserInfo",res)
          console.log(res);
          commit("SetMenu",res.menus)
          commit("SetRuleNames",res.ruleNames)
          resolve(res)

        }).catch(err=>reject(err))

       })


      },
      // 退出登录
      logout({commit}){
          // 移除cooike
          removeToken()

     // 清除用户动态
     commit ('SetUserInfo',{})



      }

    }
  })
  export default store